package middle_ware

import (
	"github.com/gin-gonic/gin"
)

// 解决跨域请求问题
func CrosMiddleWare(c *gin.Context) {
	origin := c.Request.Header.Get("origin")
	if len(origin) == 0 {
		origin = c.Request.Header.Get("Origin")
	}

	c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
	c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
	c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
	c.Writer.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE,UPDATE")
	c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
	if c.Request.Method == "OPTIONS" {
		c.AbortWithStatus(204)
		return
	}
	c.Next()
	//method := c.Request.Method
	//origin := c.Request.Header.Get("Origin")
	//if origin != "" {
	//	//接收客户端发送的origin （重要！）
	//	c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
	//	c.Writer.Header().Set("Access-Control-Allow-Headers", "sec-ch-ua-platform")
	//	//服务器支持的所有跨域请求的方法
	//	c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
	//	//允许跨域设置可以返回其他子段，可以自定义字段, 要是允许所有可以设置为 *（c.Header("Access-Control-Allow-Headers","*"）
	//	c.Header("Access-Control-Allow-Headers", "Authorization, content-type, Content-Length, X-CSRF-Token, Token,session,Access-Control-Allow-Headers,account")
	//
	//	// 允许浏览器（客户端）可以解析的头部 （重要）
	//	c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
	//	//设置缓存时间
	//	c.Header("Access-Control-Max-Age", "172800")
	//	//允许客户端传递校验信息比如 cookie (重要)
	//	c.Header("Access-Control-Allow-Credentials", "true")
	//	//c.Set("Content-Type", "application/json")
	//}
	//
	//if method == "OPTIONS" {
	//	c.AbortWithStatus(204)
	//	return
	//}
	//defer func() {
	//	if err := recover(); err != nil {
	//		fmt.Printf("Panic info is: %v\n", err)
	//	}
	//}()
	//c.Next()

}
